<html>

<head>

    <title></title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
    </style>
</head>

<script src="./utils/index.js"></script>
<body>
<canvas id="canvas"></canvas>

<script id="vertex-shader-2d" type="notjs">

  // 一个属性变量，将会从缓冲中获取数据
  attribute vec4 a_position;

  // 所有着色器都有一个main方法
  void main() {

    // gl_Position 是一个顶点着色器主要设置的变量
    gl_Position = a_position;
  }

</script>

<script id="fragment-shader-2d" type="notjs">

  // 片断着色器没有默认精度，所以我们需要设置一个精度
  // mediump是一个不错的默认值，代表“medium precision”（中等精度）
  precision mediump float;

  void main() {
    // gl_FragColor是一个片断着色器主要设置的变量
    gl_FragColor = vec4(1, 0, 0.5, 1); // 返回“瑞迪施紫色”
  }

</script>

<script>
    const canvas = document.getElementById('canvas');
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    const gl = canvas.getContext('webgl');
    gl.clearColor(0, 0, 0, 1);
    gl.clear(gl.COLOR_BUFFER_BIT);

    const verTexText = document.getElementById('vertex-shader-2d').innerText
    const fragmentText = document.getElementById('fragment-shader-2d').innerText

    const vertexShader = createShader(gl, gl.VERTEX_SHADER, verTexText)
    const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentText)

    const program = createProgram(gl, vertexShader, fragmentShader)
    console.log('program: ', program)

    const positionLocation = gl.getAttribLocation(program, 'a_position')
    console.log('a_position: ', positionLocation)

    const positionBuffer = gl.createBuffer()
    gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer)

    const positions = [
        0, 0,
        0, 0.5,
        0.7, 0,
    ]

    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW)
    console.log('positionBuffer: ', positionBuffer)

    gl.useProgram(program)

    gl.enableVertexAttribArray(positionLocation)
    gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0)

    const primitiveType = gl.TRIANGLES;
    const offset = 0;
    const count = 3;
    gl.drawArrays(primitiveType, offset, count);

</script>

</body>

</html>
